﻿using MemberManagement.Common;
using MemberManagement.Context;
using MemberManagement.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MemberManagement
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
            this.textPwd.Text = "";
            this.textPwd.Focus();
            this.Text = Helper.GetSystemTitle();
        }

        private void loginBtn_Click(object sender, EventArgs e)
        {
            ((Button)sender).Enabled = false;
            if (this.Login())
            {
                this.Hide();
                var mainForm = new MainForm();
                mainForm.FormClosed += (o, arg) =>
                {
                    this.Close();
                };
                mainForm.Show();
            }
            else
            {
                this.textPwd.Text = "";
                this.textPwd.Focus();
            }
            ((Button)sender).Enabled = true;
        }

        private bool Login()
        {
            try
            {
                var pwd = this.textPwd.Text;
                var desPwd = pwd.DESEncrypt();
                using (var db = new MyContext())
                {
                    var pwdSysConfig = db.SysConfig.FirstOrDefault(o => o.Key.ToLower() == ConstKey.PwdKey);
                    if (pwdSysConfig == null) throw new Exception("请先配置密码。参数名：password");
                    if (pwdSysConfig.Value != desPwd) throw new Exception("用户密码错误");
                    return true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
    }
}
